import {
  ApolloClient,
  createHttpLink,
  InMemoryCache,
} from '@apollo/client/core'
import { createPersistedQueryLink } from '@apollo/client/link/persisted-queries'
import Vue from 'vue'
import { sha256 } from 'crypto-hash'
import VueApollo, { ApolloProvider } from '@vue/apollo-option'

// 与 API 的 HTTP 连接
const httpLink = createHttpLink({
  uri: '/graphql',
})

// const persistedQueriesLink = createPersistedQueryLink({ sha256 })

// 缓存实现
const cache = new InMemoryCache()

// 创建 apollo 客户端
const apolloClient = new ApolloClient({
  // link: persistedQueriesLink.concat(httpLink),
  link: httpLink,
  cache,
  defaultOptions: {
    query: {
      fetchPolicy: 'network-only',
    },
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
  },
})
// provideApolloClient(apolloClient)

export const apolloProvider = new ApolloProvider({
  defaultClient: apolloClient,
})

export const useApollo = (app) => {
  // const apolloProvider = createApolloProvider({
  //   defaultClient: apolloClient,
  // })
  app.use(VueApollo, { defaultClient: apolloClient })
}

export default apolloClient
